package com.banzhi.shop.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.entity.News.News_Data;
import com.banzhi.shop.model.CallBack.NewsCallBack;
import com.banzhi.shop.model.INewsModel;
import com.banzhi.shop.model.Impl.NewsImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.DateUtil;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * 平台消息
 */
public class PingTaiFragment extends Fragment implements NewsCallBack, SwipeRefreshLayout.OnRefreshListener {
    private View view;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private INewsModel model;
    private int page = 1;
    private List<News_Data> newsdata = new ArrayList<>();
    private CommonHeadAdapter<News_Data> adapter;
    private boolean loading;
    private LinearLayoutManager layoutManager;
    private RelativeLayout rlnodata;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_ping_tai, container, false);
        setinits();
        setListeners();
        model = new NewsImpl();
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getData(page, "1", this);
        return view;
    }

    private void setinits() {
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl_listview);
        swipeRefreshLayout.setColorSchemeResources(R.color.themeColor);
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        rlnodata = (RelativeLayout) view.findViewById(R.id.rl_nodata);
    }

    private void setListeners() {
        swipeRefreshLayout.setOnRefreshListener(this);
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                if (dy > 0) //向下滚动
//                {
//                    int visibleItemCount = layoutManager.getChildCount();
//                    int totalItemCount = layoutManager.getItemCount();
//                    int pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
//
//                    if (!loading && (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
//                        loading = true;
//                        page++;
//                        LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
//                        model.getData(page, "1", PingTaiFragment.this);
//                    }
//                } else {
//                    loading = false;
//                }
//            }
//        });
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
                model.getData(page, "1", PingTaiFragment.this);
            }
        });
    }

    /**
     * @param object 获取平台消息成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        List<News_Data> data = (List<News_Data>) object;
        if (page == 1) {
            newsdata.clear();
        }
        newsdata.addAll(data);
        if (newsdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        if (adapter == null) {
            adapter = new CommonHeadAdapter<News_Data>(getContext(), R.layout.item_pingtai, newsdata) {
                @Override
                public void convert(ViewHolder holder, News_Data news_data, int position) {
                    holder.setText(R.id.tv_content, news_data.getContent());
                    holder.setText(R.id.tv_title, news_data.getTitle());
                    if(ASUtils.isCanUse(news_data.getAdd_time())){
                        holder.setText(R.id.tv_time, DateUtil.getData(news_data.getAdd_time()));
                    }
                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }


    }

    /**
     * @param object 获取平台消息失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        if ("400".equals(jsonObject.optString("code"))) {
            if (page == 1) {
                rlnodata.setVisibility(View.VISIBLE);
            }else{
                ToastUtils.makeToastShort(jsonObject.optString("msg"));
            }
        }else{
            NoTokenUtils.loginOut(getActivity(), jsonObject);
            ToastUtils.makeToastShort(jsonObject.optString("msg"));
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getData(page, "1", this);
    }
}
